<!-- 排课表 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="所属校区">
        <campusSelect v-model="queryParams.campus" class="form-select" />
      </el-form-item>
      <el-form-item label="是否兼职">
        <el-select
          v-model="queryParams.grade"
          placeholder="请选择是否兼职"
          clearable
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属校区">
        <campusSelect v-model="queryParams.campus" class="form-select" />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleQuery('minus')">
          上周
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleQuery"> 本周 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleQuery('add')">
          下周
        </el-button>
      </el-col>
      <el-col :span="1.5" :offset="14">颜色: </el-col>
      <el-col :span="1.5">
        <el-link type="danger" :underline="false"> 新课时 </el-link>
      </el-col>
      <el-col :span="1.5">
        <el-link type="success" :underline="false"> 已确认 </el-link>
      </el-col>
      <el-col :span="1.5">
        <el-link type="info" :underline="false"> 教师请假 </el-link>
      </el-col>
      <el-col :span="1.5">
        <el-link type="warning" :underline="false"> 陪读 </el-link>
      </el-col>
    </el-row>
    <div
      class="data-container"
      v-for="item in dataList"
      v-loading="loading"
      :key="item.teacherId"
    >
      <div class="name-list">
        {{ item.teacherName }} {{ item.subjectName }} {{ item.roleName }}
        {{ item.phone || "无电话" }}
      </div>

      <el-table
        :data="item.sysClassViewsList"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <!-- 动态生成日期列 -->
        <el-table-column
          v-for="(date, index) in dateColumns"
          :key="index"
          :label="date"
        >
          <template #default="{ row }">
            <div v-if="row.sysClassViewList[index].sysClass">
              <el-link
                :type="
                  row.sysClassViewList[index].sysClass.status == 0
                    ? 'danger'
                    : row.sysClassViewList[index].sysClass.status == 1
                    ? 'success'
                    : row.sysClassViewList[index].sysClass.status == 3
                    ? 'info'
                    : row.sysClassViewList[index].sysClass.status == 4
                    ? 'warning'
                    : ''
                "
                :underline="false"
                @click="getDetail(row.sysClassViewList[index].sysClass)"
              >
                {{ row.sysClassViewList[index].sysClass.customerName }}
              </el-link>
            </div>
            <div v-else>
              <el-link
                type="primary"
                :underline="false"
                @click="
                  openAddDialog(
                    item.teacherId,
                    row.sysClassViewList[index].classTimeSlot,
                    date
                  )
                "
              >
                {{ row.sysClassViewList[index].classTimeSlot }}
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="课程信息"
      :visible.sync="dialog.visible"
      @close="closeDetailDialog"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item>
          <template slot="label"> 状态 </template>
          {{
            dialog.data.status == 0
              ? "新课时"
              : dialog.data.status == 1
              ? "已确认"
              : dialog.data.status == 3
              ? "教师请假"
              : dialog.data.status == 4
              ? "陪读"
              : ""
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 最大人数 </template>
          {{ dialog.data.maxNum }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 原班级 </template>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 学员与合同 </template>
          {{ formatStudent(dialog.data.sysClassLabelList) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 日期 </template>
          {{ dialog.data.classDate }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 时间 </template>
          {{ dialog.data.classTimeSlot }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 上课教师 </template>
          {{ dialog.data.teacherName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 学科 </template>
          {{ dialog.data.subjectName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 年级 </template>
          {{ dialog.data.grade }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="confirmClass(dialog.data.id, 'add')"
          type="primary"
          v-if="dialog.data.status == 0"
        >
          确认排课
        </el-button>
        <el-button
          @click="confirmClass(dialog.data.id, 'leave')"
          type="primary"
          v-if="dialog.data.status == 0"
        >
          教师请假
        </el-button>
        <el-button
          @click="confirmClass(dialog.data.id, 'del')"
          type="danger"
          v-if="dialog.data.status == 0"
        >
          删除课程
        </el-button>
        <el-button @click="closeDetailDialog">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增课程"
      :visible.sync="addDialog.visible"
      @close="closeAddDialog"
    >
      <div>
        <span>连续排课周数</span>
        <el-select
          v-model="addDialog.weekNum"
          placeholder="请选择"
          clearable
          class="add-select"
        >
          <el-option label="1" :value="1" />
          <el-option label="2" :value="2" />
          <el-option label="3" :value="3" />
          <el-option label="4" :value="4" />
          <el-option label="5" :value="5" />
          <el-option label="6" :value="6" />
          <el-option label="7" :value="7" />
          <el-option label="8" :value="8" />
        </el-select>
        <p>依顺序添加，例如添加5周，在第4周出现课时不足，则前3周依然生效</p>
        <p class="add-font">请选择排课对象</p>
      </div>
      <el-table :data="addDialog.data" border stripe>
        <!-- 动态生成日期列 -->
        <el-table-column prop="contractCode" label="合同编号" align="center" />
        <el-table-column
          prop="contractTypeName"
          label="合同类型"
          align="center"
        />
        <el-table-column prop="customerName" label="姓名" align="center" />
        <el-table-column prop="customerCode" label="客户编号" align="center" />
        <el-table-column prop="campusName" label="校区名称" align="center" />
        <el-table-column label="年级" align="center">
          <template #default="{ row }">
            {{ formatGrade(row.grade) }}
          </template>
        </el-table-column>
        <el-table-column prop="subjectClassName" label="科目" align="center" />
        <el-table-column prop="subjectClassTime" label="课时" align="center" />
        <el-table-column
          prop="duringClassTime"
          label="已上课时"
          align="center"
        />
        <el-table-column
          prop="NotDuringClassTime"
          label="已排课时(未上)"
          align="center"
          min-width="140"
        />
        <!-- <el-table-column prop="teacherName" label="赠送" align="center" >
          </el-table-column> -->
        <el-table-column
          prop="RemainingClassTime"
          label="剩余课时"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="addClass(row.id)">
              选择该明细创建课时
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getClassContract">
          合同明细
        </el-button>
        <el-button @click="closeAddDialog">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import {
  getList,
  getDetail,
  getTeacherContrat,
  addClass,
  confirmClass,
  askForLeave,
  delClass,
} from "@/api/course/sheet";
import userSelect from "@/components/Select/userSelect.vue";
import campusSelect from "@/components/Select/campusSelect.vue";

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        customerCode: "", //客户编号
        grade: "", //年级
        customerName: "", //姓名
        status: "", //签约状态
        phone: "", //手机号码
        sex: "", //性别
        customerSource: "", //线索客户来源
        educationlAdviser: "", //教育顾问
        campus: "", //所属校区
        pageNum: 1,
        pageSize: 10,
      },

      dialog: {
        visible: false, // 控制对话框的显示
        data: {}, // 对话框表单数据
      },
      addDialog: {
        visible: false, // 控制对话框的显示
        data: [], // 对话框表单数据
        weekNum: 1, //连续排课周数
        id: null, // 教师ID
        classTimeSlot: "", // 时间段
        classDate: "", // 课程日期
      },

      // 日期列（表头）
      dateColumns: [], // 生成7天的日期

      // 时间段
      timeRanges: [
        "8:00-10:00",
        "10:10-12:10",
        "12:50-14:50",
        "15:00-17:00",
        "17:30-19:30",
        "19:40-21:40",
      ],
      //当年的周
      nowWeek: null,
      // 表格数据
      tableData: [],
    };
  },
  components: {
    userSelect,
    campusSelect,
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.loading = true;
      const { nowWeek } = this;
      getList({ ...this.queryParams, nowWeek }).then((res) => {
        this.dataList = res.rows;
        this.dateColumns = res.weekRange;
        this.nowWeek = res.nowWeek;
        this.total = res.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(week) {
      this.queryParams.pageNum = 1;

      if (week == "minus") {
        this.nowWeek = this.nowWeek - 1;
      } else if (week == "add") {
        this.nowWeek = this.nowWeek + 1;
      } else {
        this.nowWeek = "";
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.nowWeek = "";
      this.handleQuery();
    },

    getDetail({ id }) {
      getDetail(id)
        .then((res) => {
          if (res.code == 200) {
            this.dialog.data = res.data;
            this.dialog.visible = true;
          }
        })
        .catch((error) => {
          this.$message.error("获取排课详情时发生错误: " + error.message);
        });
    },

    formatStudent(students) {
      return _.map(students, "customerName").join(", ");
    },

    closeDetailDialog() {
      this.dialog.visible = false;
      this.dialog.data = {};
    },

    openAddDialog(id, classTimeSlot, date) {
      this.addDialog.visible = true;
      this.addDialog.id = id;
      this.addDialog.classTimeSlot = classTimeSlot;
      this.addDialog.classDate = date;
    },

    getClassContract() {
      getTeacherContrat({ teacherId: this.addDialog.id }).then((res) => {
        if (res.code == 200) {
          this.addDialog.data = res.rows;
        }
      });
    },

    formatGrade(grade) {
      const gradeOpiton = [
        { value: 0, label: "小一" },
        { value: 1, label: "小二" },
        { value: 2, label: "小三" },
        { value: 3, label: "小四" },
        { value: 4, label: "小五" },
        { value: 5, label: "小六" },
        { value: 6, label: "初一" },
        { value: 7, label: "初二" },
        { value: 8, label: "初三" },
        { value: 9, label: "高一" },
        { value: 10, label: "高二" },
        { value: 11, label: "高三" },
        { value: 12, label: "高四" },
      ];
      return _.find(gradeOpiton, { value: grade })?.label || "未知年级";
    },

    addClass(contractLabelId) {
      const data = {
        contractLabelId,
        week: this.addDialog.weekNum,
        classTimeSlot: this.addDialog.classTimeSlot,
        teacherId: this.addDialog.id,
        classDate: this.addDialog.classDate,
      };

      addClass(data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("新增排课成功");
            this.addDialog.visible = false;
            this.addDialog.data = [];
            this.addDialog.weekNum = 1;
            this.addDialog.id = null;
            this.addDialog.classTimeSlot = "";
            this.addDialog.classDate = "";
            // 重新获取列表
            this.getList();
          } else {
            this.$message.error("新增排课失败: " + res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("新增排课时发生错误: " + error.message);
        });
    },

    closeAddDialog() {
      this.addDialog.visible = false;
      this.addDialog.data = [];
      this.addDialog.weekNum = 1;
      this.addDialog.id = null;
      this.addDialog.classTimeSlot = "";
      this.addDialog.classDate = "";
    },

    confirmClass(id, type) {
      if (type == "leave") {
        askForLeave({ id }).then((res) => {
          if (res.code == 200) {
            this.$message.success("教师请假成功");
            this.closeDetailDialog();
            // 重新获取列表
            this.getList();
          }
          return;
        });
      } else if (type === "add") {
        confirmClass({ id }).then((res) => {
          if (res.code == 200) {
            this.$message.success("课程确认成功");
            this.closeDetailDialog();
            // 重新获取列表
            this.getList();
          }
        });
      } else if (type === "del") {
        delClass(id).then((res) => {
          if (res.code == 200) {
            this.$message.success("课程删除成功");
            this.closeDetailDialog();
            // 重新获取列表
            this.getList();
          }
          return;
        });
      }
    },
  },
};
</script>
<style scoped lang="scss">
.customer-container {
  margin-bottom: 10px;
  font-size: 18px;
  color: #606266;
}

.data-container {
  width: 100%;
  height: auto;
  border: 1px solid #ddd;
  display: flex;
  margin-top: 10px;

  .name-list {
    width: 40px;
    // height: 100%;
    line-height: 40px;
    background-color: #f5f5f5;
    padding: 10px 0;

    font-weight: bold;
    border-right: 1px solid #ddd;
    writing-mode: vertical-lr;
    text-align: center;
  }
}

.add {
  &-select {
    width: 100px;
    margin: 0 10px;
  }
  &-font {
    font-size: 24px;
    color: #606266;
    margin-top: 20px;
  }
}
</style>
